from django.shortcuts import render,redirect, reverse
import pymysql
from django.http import HttpResponse
from Dj030101.settings import *
from .myclass.signin import *
# Create your views here.

# def index(request):
#     #实例化一个连接
#     mysql_db = pymysql.connect(host=DB_HOST,user=DB_USER,password=DB_PASSWORD,database=DB_NAME)
#
#     #准备sql语句
#     sql = "select * from Login"
#     cursor = mysql_db.cursor()
#     try:
#         cursor.execute(sql)
#         #获取结果
#         results = cursor.fetchall()
#         #返回
#         #print(results)
#         return HttpResponse(str(results))
#
#     except Exception as e:
#         mysql_db.rollback()
#         return HttpResponse("获取数据出现异常,具体原因："+str(e))
#
#     cursor.close()
#     mysql_db.close()

def index(request):
    return redirect(reverse('login'))

#======== 传统写法 ======
"""
def login(request):
    #登录页面,:param request:,:return:
    #如果是GET方式，打开登录界面
    if request.method == 'GET':
        return render(request, 'login.html')
    #如果是POST方式打开，则是验证输入的用户名和密码
    elif request.method == "POST":
        #定义一个变量存储登录过程中错误的信息
        error_info = ""
        logins = []

        #1、获取数据的用户名和密码
        login_id = request.POST.get('login')
        login_pwd = request.POST.get('password')
        print('登录名:', login_id)
        print('密码:', login_pwd)
        #2.获取数据库中数据
        mysql_db = pymysql.connect(host=DB_HOST,user=DB_USER,password=DB_PASSWORD,database=DB_NAME)
        sql = Select LoginId,LoginPwd,UserName,IsEnable,PositionName from Login As T1 INNER JOIN Position As T2 on T1.PositionId = T2.PositionId
        
        cursor = mysql_db.cursor()
        try:
            #执行sql获取结果
            cursor.execute(sql)
            logins = cursor.fetchall()
            print(logins)
            print(len(logins))

        except Exception as e:
            error_info = "联系数据库出现异常,具体原因:" + str(e)
        finally:
            mysql_db.close()

        #3.用输入的账号在数据库中判断
        for index in range(len(logins)):
            #如何登录名匹配
            if logins[index][0] == login_id:
                #判断是否禁用
                if logins[index][3] == 0:
                    error_info = "账号已禁用！请联系管理员"
                    break
                #如果密码匹配：
                if logins[index][1] == login_pwd:
                    #判断职位
                    return redirect(reverse('cashier'))
                else:
                    error_info = "密码错误!!!"
                    break
            #判断用户名是否存在
            if index == len(logins) - 1:
                error_info = "登录账号不存在!"


        #以下场景还没有做，比如：登录名不存在，密码错误已经禁用，启用状态是否开启，根据职位做相应的页面跳转
        return render(request,'login.html',context={'loginId':login_id,
                                                    'loginPwd':login_pwd,
                                                     'info': error_info})
"""
#======== 实例化身份验证的对象 ==========
login_obj = UserSignin() #全局的

#========= 类的写法 ==========
def login(request):
    # 如果是GET方式，打开登录界面
    if request.method == 'GET':
        return render(request, 'login.html')
    # 如果是POST方式打开，则是验证输入的用户名和密码
    elif request.method == "POST":
        #获取登录的用户名和密码并赋值到实例变量
        login_obj.loginId = request.POST.get('login')
        login_obj.loginPwd = request.POST.get('password')
        #进行身份验证
        login_obj.signin()
        #根据结果返回
        if login_obj.signin_result:  #如果结果是True
            #判断职位
            if "收银" in login_obj.position_name:
                return redirect(reverse('cashier') + "?username=" + login_obj.current_username)
            elif "管理员" in login_obj.position_name:
                return redirect(reverse('main') + "?username=" + login_obj.current_username)

        else:
            return render(request, 'login.html', context={'loginId': login_obj.loginId,
                                                          'loginPwd': login_obj.loginPwd,
                                                          'info': login_obj.error_info})

def cashier(request):
    """
    收银页面
    :param request:
    :return:
    """
    #获取url中的用户名
    username = request.GET.get('username')
    if username:
        return render(request,'cashier.html',context={'username': username})
    else:
        return redirect(reverse('login'))

def add_product(request):
    """
    :param request:
    :return:
    """
    return render(request,'cashier.html')

def delete_product(request):
    """
    :param request:
    :return:
    """
    return render(request,'cashier.html')

def get_return(request):
    """
    :param request:
    :return:
    """
    return render(request,'cashier.html')

def cashier_cancel(request):
    """
    :param request:
    :return:
    """
    # 获取url中的用户名


def cashier_submit(request):
    """
    :param request:
    :return:
    """
    return render(request,'cashier.html')

def main(request):
    """
    管理员主页面
    :param request:
    :return:
    """
    username = request.GET.get('username')
    if username:
        return render(request, 'main.html', context={'username': username})
    else:
        return redirect(reverse('login'))

def sales_query(request):
    """
    管理员主页面
    :param request:
    :return:
    """
    return render(request,'sales_query.html')

def salesdetail_query(request):
    """
    明细查询页面
    :param request:
    :return:
    """
    #会将当前名称空间中所有的变量名全部传递给salesdetail_query.html页面
    return render(request,'salesdetail_query.html')